# 阻塞循环执行程序，直到成功才退出
function run-loop () {
    local cmd="$@"
    local tmp_cmd_file="/tmp/$$.loopdo"
    (
    cat <<EOF
    rm $tmp_cmd_file
    while true;
    do
        ${cmd} && break
        sleep 1
    done
EOF
) >> $tmp_cmd_file
    ## 要求source，以执行拓展命令
    source $tmp_cmd_file
}
alias looprun="run-loop"


# 根据文件列表执行批量操作
function run-batch-cmd-with-file-list {
function run-batch-cmd-with-file-list-help {
cat <<EOF
$0 : batchly run cmds with a file list.
arg1 : the script you want to run
arg2 : the file list
arg3 : same args you want to append

---
e.g. :
   git status -s | awk '{print\$2}' > /tmp/gs.list
   $0 'git add' /tmp/gs.list
EOF
}
    local cmd="$1"
    local flist="$2"
    local after="$3"

    #if [ $(require $cmd) ]; then
    #    run-batch-cmd-with-file-list-help $0 ; return
    #fi
    if [ ! -f "$flist" ]; then
        run-batch-cmd-with-file-list-help $0 ; return
    fi
    local tmplist=/tmp/.$$.${USER}.cmdlist
    (
    cat <<EOF
    awk '{print "$cmd " "'\''" \$0 "'\''" "$after"}' $flist
EOF
) > $tmplist
#cat $tmplist
#    rm $tmplist
#    cat $flist |while read line
#    do
#        (
#        cat <<EEOF
#$cmd "$line" $after
#EEOF
#        ) >> $tmplist
#        #`echo $cmd` $line
#   done
    #echo $tmplist
    source $tmplist > $tmplist.2
    source $tmplist.2
    rm $tmplist $tmplist.2
}

# 执行，并且打印log
function run-and-log () {
    local cmd="$1"
    local log="$2"
    if [ -z "$cmd" -o -z "$log" ]; then
        echo "cmd logfile"
        return
    fi
    local tmp=/tmp/.dal.$$.sh
cat <<EOF > $tmp
$cmd 2>&1 | tee $log
EOF
    ## 要求source，以执行拓展命令
    source $tmp
    rm $tmp -rf
}
alias logrun="run-and-log"
